package com.huika.dealontop.control.base.extend;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.dealontop.control.base.extend.impl.ILoadableListProvider;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.DebugTool;
import com.huika.dealontop.utils.UIUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import java.util.List;

/**
 * Author: Victor Wu
 * Email: victor-wu*foxmail.com
 * Time: 2015/11/13 11:25
 * Description: 具有加载更多功能的适配器
 */
public class BaseLoadMoreAdapter<T, E> extends BaseAdapter implements AbsListView.OnScrollListener, Response.Listener<RequestResult<T>> {

    private final String TAG = "BaseLoadMoreAdapter";

    protected List<E> mData;

    protected LoadMoreHolder mLoadMoreHolder;

    private ListView mListView;

    public ILoadableListProvider<T, E> getListProvider() {
        return mListProvider;
    }

    /**
     * 必须在setAdapter 之前设置
     *
     * @param listProvider
     */
    public void setListProvider(ILoadableListProvider<T, E> listProvider) {
        this.mListProvider = listProvider;
    }

    private ILoadableListProvider<T, E> mListProvider;

    private PauseOnScrollListener mPauseOnScrollListener;

    public BaseLoadMoreAdapter(ListView listView, ILoadableListProvider<T, E> listProvider) {
        this(listView, null, listProvider);
    }

    public BaseLoadMoreAdapter(ListView listView, List<E> data, ILoadableListProvider<T, E> listProvider) {
        this.mData = data;
        this.mListView = listView;
        this.setListProvider(listProvider);
        //添加加更多显示
        mListView.addFooterView(getLoadMoreHolder().getRootView());

        // 有没有加载更多的功能 更新ui显示
        getLoadMoreHolder().refreshView(needToLoadMore() ? LoadMoreHolder.STATE_LOADING : LoadMoreHolder.STATE_EMPTY);

        mPauseOnScrollListener = new PauseOnScrollListener(ImageLoader.getInstance(), true, true);

        mListView.setOnScrollListener(this);
    }

    @Override
    public int getCount() {
        if (mData != null) {
            return mData.size();
        }
        return 0;
    }

    @Override
    public E getItem(int position) {
        if (mData != null) {
            return mData.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        if (this.mListProvider == null) {
            DebugTool.e(TAG, new IllegalStateException("ILoadableListProvider == null !!"));
            return null;
        }
        BaseViewHolder<E> holder = null;
        if (convertView == null) {
            // 没有复用
            holder = this.mListProvider.getItemViewHolder(position);
            convertView = holder.getRootView();
        } else {
            // 有复用
            holder = (BaseViewHolder<E>) convertView.getTag();
        }
        //刷新数据
        holder.setData(mData.get(position), position);

        return convertView;
    }

    public void setData(List<E> data) {
        //FooterView 也会影响数据刷新
        mListView.removeFooterView(mLoadMoreHolder.getRootView());
        if (this.mData != null) {
            this.mData.clear();
        }
        this.mData = data;
        notifyDataSetChanged();

        //有没有加载更多的功能 更新ui显示
        getLoadMoreHolder().refreshView(needToLoadMore() ? LoadMoreHolder.STATE_LOADING : LoadMoreHolder.STATE_EMPTY);

        //重新添加footedView
        mListView.addFooterView(getLoadMoreHolder().getRootView());
    }


    /**
     * 如果子类有加载更多的功能，那么必须实现加载更多的方法<br/>
     *
     * @return
     */
    protected RequestProtocol onLoadMoreData() {
        if (this.mListProvider != null) {
            return this.mListProvider.onLoadMoreData();
        }
        return null;
    }

    /**
     * 加载更多的 holder
     *
     * @return
     */
    private LoadMoreHolder getLoadMoreHolder() {
        if (mLoadMoreHolder == null) {
            mLoadMoreHolder = new LoadMoreHolder(UIUtils.getContext());
        }

        return mLoadMoreHolder;
    }

    /**
     * 是否需要加载更多的功能，默认需要，
     *
     * @return
     */
    private boolean needToLoadMore() {
        if (mListProvider != null) {
            //如果子类不希望加载更多的功能，去实现这个方法 并返回 false
            return mListProvider.needToLoadMore();
        }
        //默认有加载更多
        return true;
    }

    /**
     * 去加载更多的数据
     */
    public void loadMoreData() {

        if (this.mListProvider == null) {
            DebugTool.e(TAG, new IllegalStateException("ILoadableListProvider == null !!"));
            return;
        }
        //防止重复
        cancelLoadMore();

        RequestProtocol requestProtocol = this.mListProvider.onLoadMoreData();

        if (requestProtocol == null) {
            return;
        }
        //异步加载数据
        FormResultRequest<T> request = new FormResultRequest<>(requestProtocol.getUrl(),
                BaseLoadMoreAdapter.this,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        volleyError.printStackTrace();
                        getLoadMoreHolder().setData(LoadMoreHolder.STATE_ERROR);
                    }
                }, new TypeToken<RequestResult<T>>() {
        }.getType());
        request.setRequestParams(requestProtocol);
        VolleyRequestManager.addRequest(request, this);
    }

    /**
     * 终止正在执行的任务
     */
    public void cancelLoadMore() {
        VolleyRequestManager.cancelAll(this);
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
            //滚动到底部
            int lastVisiblePosition = absListView.getLastVisiblePosition();
            DebugTool.print("lastVisiblePosition : " + lastVisiblePosition);
            if (lastVisiblePosition == (absListView.getCount() - 1)) {
                if (needToLoadMore()) {
                    // 有加载更多的功能
                    getLoadMoreHolder().refreshView(LoadMoreHolder.STATE_LOADING);
                    // 去加载更多数据
                    loadMoreData();
                } else {
                    // 没有加载更多的功能 更新ui显示
                    getLoadMoreHolder().setData(LoadMoreHolder.STATE_EMPTY);
                }
            }
        }
        mPauseOnScrollListener.onScrollStateChanged(absListView, scrollState);
    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i2, int i3) {
        mPauseOnScrollListener.onScroll(absListView, i, i2, i3);
    }

    @Override
    public void onResponse(RequestResult<T> requestResult) {

        if (this.mListProvider == null) {
            // 加载更多的View隐藏
            //getLoadMoreHolder().setData(LoadMoreHolder.STATE_EMPTY);
            DebugTool.e(TAG, new IllegalStateException("ILoadableListProvider == null !!"));
            return;
        }
        List<E> moreData = null;
        if (requestResult != null) {
            moreData = mListProvider.getListData(requestResult.getRs());
        }
        // 对数据进行判断
        if (moreData == null || moreData.size() == 0) {
            // 加载更多的View隐藏
            getLoadMoreHolder().setData(LoadMoreHolder.STATE_EMPTY);
        } else {
            int size = moreData.size();

            //检查是否有下一页
            getLoadMoreHolder().setData(size >= mListProvider.getPageSize() ? LoadMoreHolder.STATE_LOADING : LoadMoreHolder.STATE_EMPTY);

            // 把数据加到 list数据中
            mData.addAll(moreData);

            // UI刷新
            notifyDataSetChanged();
        }
    }
}
